
import request from './request'
import {requestFilter} from '@/utils/permiss'
// 过滤请求参数
const filterParams = (params = {}) => {
    let query = {}
    // 过滤空字符串 undefined null
    const filterEmpty = (value => value !== null && typeof value !== undefined && value !== "")
    if (Object.prototype.toString.call(params) === '[object FormData]' || Array.isArray(params)) {
        // form表单或者数组格式直接赋值
        query = params
    } else {
        // 对象格式
        for (let key in params) {
            if (filterEmpty(params[key])) {
                query[key] = params[key]
            }
        }
    }
    return query
}
/**
 *
 * @param url 地址
 * @param params 参数
 * @param methods={isFilter:当前接口是否权限过滤}
 * @returns {Promise<unknown>}
 */
export function get(url, params, methods = {}) {
    return new Promise((resolve, reject) => {
        if (methods.isFilter && !requestFilter(url)) {
            resolve({})
            return
        }
        const query = filterParams(params)
        request.get(url, {params: query, ...methods}).then(res => {
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}

export function post(url, params, methods = {}) {
    return new Promise((resolve, reject) => {
        if (methods.isFilter && !requestFilter(url)) {
            resolve({})
        }
        // const query = filterParams(params)
        request.post(url, params, methods).then(res => {
            resolve(res)
        }).catch(error => {
            reject(error)
        })
    })
}

